<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <div style="color:#ff0000">{{ errMessage }}</div>
  </div>
</template>
<script>
import Schema from "async-validator";//校验包
export default {
  name: "el-form-item",
  inject: ["elForm"],//去找父级的_provided属性，合并到自己身上，拿校验规则
  props: {
    label: {
      //标签
      type: String,
      default: "",
    },
    prop: String, //当前校验的属性
  },
  data() {
    return { errMessage: "" };
  },
  mounted() {
    console.log(2,this.elForm)//拿到
    //发布订阅，挂载后监听子组件发射的校验事件
    this.$on("validate", function () {
      // console.log(this.prop)
      this.validate();
    });
  },
  methods: {
    //在el-form-item中需要校验当前你输入的内容是否符合规范，用户更改对应的输入框，对应的el-form-item应该知道
    validate() {
      //校验规则要从父组件拿到
      if (this.prop) {
        let rule = this.elForm.rules[this.prop]; //通过名字找到规则
        let newValue = this.elForm.model[this.prop];
        // console.log(rule,newValue)
        //el-form使用了验证库 async-validator
        //npm install async-validator
        let descriptor = {
          //骨架，当前属性的描述
          [this.prop]: rule,
        };
        //用schema库实时校验
        let schema = new Schema(descriptor); //通过描述信息创建一个骨架
        return schema.validate({ [this.prop]: newValue }, (err, res) => {
          if (err) {
            this.errMessage = err[0].message;
          } else {
            this.errMessage = "";
          }
        });
        // let obj = {a:1}
        // let obj1 = {[obj.a]:2} => obj=>{1:2}
      }
    },
  },
};
</script>